<template>
  <el-form ref="emailLoginForm" :model="emailLoginForm" :rules="phoneLoginRules" auto-complete="on">
    <el-form-item prop="email">
      <el-input ref="email" v-model="emailLoginForm.email" placeholder="邮箱" name="email" type="text" auto-complete="on" />
    </el-form-item>

    <el-form-item prop="code" class="form-item-code">
      <div class="flex">
        <el-input ref="code" v-model="emailLoginForm.code" maxlength="6" class="flex1" type="text" placeholder="邮箱验证码" name="code" />
        <SendCode ref="code" @run="handleSendCode" />
      </div>
    </el-form-item>

    <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 20px" @click.native.prevent="handleLogin"> 登 录 </el-button>
  </el-form>
</template>

<script>
import { validateMail } from '@/utils/validate.js'
import { loginApi } from '@/api/api.js'
import SendCode from '@/components/SendCode'

export default {
  name: 'LogByEmail',
  components: {
    SendCode
  },
  props: {
    redirect: {
      type: String,
      default: '/'
    }
  },
  data() {
    return {
      loading: false,
      // 手机验证登录下表单
      emailLoginForm: {
        email: '',
        code: ''
      },
      // 手机验证登录表单验证
      phoneLoginRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { trigger: 'blur', validator: validateMail }
        ],
        code: [{ required: true, trigger: 'blur', message: '请输入邮箱验证码' }]
      }
    }
  },
  methods: {
    // 发送短信验证码
    handleSendCode() {
      this.$refs.emailLoginForm.validateField('email', (valid) => {
        if (!valid) {
          this.$request(loginApi.sendLoginEmailCode, { email: this.emailLoginForm.email }).then(() => {
            this.$refs.code.start()
            this.$notify({
              title: '成功',
              message: '登录邮箱验证码已发送，请及时查收',
              //message: `${res.msg}`,
              type: 'success'
            })
          })
        }
      })
    },
    // 登录事件
    handleLogin() {
      this.$refs.emailLoginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/loginByEmail', this.emailLoginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-code {
  ::v-deep.el-form-item__content {
    background: #fff;
  }
}
</style>
